package com.jungle.sp.daily.controller;

import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jungle.sp.daily.entity.User;
import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {


    /**
     * 1、注解方式实现
     */
    @JsonView(User.InternalView.class)
    @GetMapping("/query")
    public User query() {
        return new User(1L, "pack", "四川乌鲁木齐市", "123456", "152528202504096514", "pack@qq.com");
    }


    /**
     * 编程方式实现
     */
    @GetMapping("/getUser")
    public MappingJacksonValue getUser() {
        User user = new User(1L, "pack", "四川乌鲁木齐市", "123456",
                "152528202504096514", "pack@qq.com");
        MappingJacksonValue value = new MappingJacksonValue(user);
        value.setSerializationView(User.PublicView.class);
        return value;
    }


    /**
     * 当我们不希望某些字段被反序列化时，我们也可以通过该视图技术来限制
     */
    @PostMapping("/deserialize_json")
    public User deserialize(@RequestBody String json) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        return mapper
                .readerWithView(User.PublicView.class)
                .forType(User.class)
                .readValue(json);
    }
}